<template>
  <!-- 使用过渡组件实现淡入淡出效果 -->
  <transition :name="randomEffect">
    <!-- 动态绑定图片的 src 属性 -->
    <img :src="'/song/' + id + '/' + imageUrl" alt="Song Image" v-if="imageUrl" @error="handleImageError" />
  </transition>
</template>

<script setup>
import { defineProps, ref, watch } from 'vue';

// 定义接收的 prop
const props = defineProps({
  imageUrl: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: ''
  }
});

// 定义一些背景图的 URL 数组
const backgroundImages = ref([
  '1.png',
  '2.png',
  '3.png',
  '4.png'
]);

// 定义随机特效
// const effects = ['fade', 'flip', 'rotate', 'slide', 'zoom'];
const effects = ['fade'];
const randomEffect = ref('fade');

const imgError = ref(false);
// 处理图片加载错误的函数
const handleImageError = (event) => {
  imgError.value = true;
  event.target.src = '/song/' + props.id + '/' + backgroundImages.value[0];
  randomImage(event);
};

const randomImage = (event) => {
  setTimeout(() => {
    if (imgError.value) {
      // 随机选择一张背景图
      const randomIndex = Math.floor(Math.random() * backgroundImages.value.length);
      const image = backgroundImages.value[randomIndex];
      // 将图片的 src 属性替换为随机背景图的 URL
      event.target.src = '/song/' + props.id + '/' + image;
      randomImage(event);
    }
  }, 3000, event);
};

watch(() => props.imageUrl, () => {
  imgError.value = false;
  const randomIndex = Math.floor(Math.random() * effects.length);
  randomEffect.value = effects[randomIndex];
}, { immediate: true });
</script>

<style scoped>
/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

/* 翻转动画 */
.flip-enter-active,
.flip-leave-active {
  transition: transform 0.5s;
  transform-style: preserve-3d;
}

.flip-enter,
.flip-leave-to {
  transform: rotateY(90deg);
}

/* 旋转动画 */
.rotate-enter-active,
.rotate-leave-active {
  transition: transform 0.5s;
}

.rotate-enter,
.rotate-leave-to {
  transform: rotate(360deg);
}

/* 滑动动画 */
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.5s;
}

.slide-enter {
  transform: translateX(-100%);
}

.slide-leave-to {
  transform: translateX(100%);
}

/* 缩放动画 */
.zoom-enter-active,
.zoom-leave-active {
  transition: transform 0.5s;
}

.zoom-enter {
  transform: scale(0);
}

.zoom-leave-to {
  transform: scale(0.5);
}
</style>